#include "PushHandle.h"

#include "DDStruct.h"

string GetVal(HANDLE_SESSION sess, int fidId)
{
	char fieldVal[512]{};
	int fieldLen = sizeof(fieldVal);

	Fix_GetItem(sess, fidId, fieldVal, fieldLen, 0);
	return fieldVal;
}

bool PushCallBackFunc(HANDLE_CONN conn, HANDLE_SESSION sess, int64_t nSubs, void *pData)
{
	fmt::print("委托推送连接句柄:{}, 会话session={}, 订阅句柄={}\n", conn, sess, nSubs);

	cout << Fix_IsStruct(sess) << endl;
	char outstr[512]{};
	int outlen = sizeof(outstr);
	Fix_GetItemBuf(sess, outstr, outlen, 0);

	DDPushOrder *order = (DDPushOrder *)outstr;
	auto logstr = fmt::format("(KHH:{})(WTH:{})(JYS:{})(HYDM:{})(MMFX:{})(KPBZ:{})(CXBZ:{})(WTSJ:{})(WTSL:{})(WTJG:{})(SBJG:{})(JGSM:{})\n",
							  order->KHH, order->WTH, order->JYS, order->HYDM, order->MMFX, order->KPBZ, order->CXBZ, order->WTSJ, order->WTSL, order->WTJG, order->SBJG, order->JGSM);

	fmt::print("[push]{}", logstr);

	logger->info("[push order]{}", logstr);

	return true;
}

bool TradePushCallBackFunc(HANDLE_CONN conn, HANDLE_SESSION sess, int64_t nSubs, void *pData)
{
	fmt::print("成交推送连接句柄:{}, 会话session={}, 订阅句柄={}\n", conn, sess, nSubs);

	cout << Fix_IsStruct(sess) << endl;
	char outstr[512]{};
	int outlen = sizeof(outstr);
	Fix_GetItemBuf(sess, outstr, outlen, 0);

	DDPushTrade *trade = (DDPushTrade *)outstr;
	auto logstr = fmt::format("(KHH:{})(WTH:{})(JYS:{})(HYDM:{})(MMFX:{})(KPBZ:{})(CXBZ:{})(WTSJ:{})(WTSL:{})(WTJG:{})(CJBH:{})(JGSM:{})\n",
							  trade->KHH, trade->WTH, trade->JYS, trade->HYDM, trade->MMFX, trade->KPBZ, trade->CXBZ, trade->CJSJ, trade->CJSL, trade->CJJG, trade->CJBH, trade->JGSM);

	fmt::print("[push]{}", logstr);

	logger->info("[push trade]{}", logstr);

	return true;
}

void SubPushOrder(HANDLE_SESSION sess, const char *khh, const char *token)
{
	FIX_INT64 nSubs = -1;
	bool isSuccess = Fix_SubscribeByToken(sess, nSubs, khh, token, (void *)PushCallBackFunc, nullptr);
	if (isSuccess)
	{
		fmt::print(fg(fmt::color::cadet_blue), "委托推送订阅成功:{}\n", nSubs);
		logger->info("委托推送订阅成功, 订阅句柄={}\n", nSubs);
	}
	else
	{
		logger->info("委托推送订阅失败，{}\n", Geterrmsg(sess));
	}
}

void SubPushTrade(HANDLE_SESSION sess, const char *khh, const char *token)
{
	FIX_INT64 nSubs = -1;
	bool isSuccess = Fix_SubscribeByToken(sess, nSubs, khh, token, (void *)TradePushCallBackFunc, nullptr);
	if (isSuccess)
	{
		fmt::print(fg(fmt::color::cadet_blue), "成交推送订阅成功:{}\n", nSubs);
		logger->info("成交推送订阅成功, 订阅句柄={}\n", nSubs);
	}
	else
	{
		logger->info("成交推送订阅失败，{}\n", Geterrmsg(sess));
	}
}